<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { useQualificationAddOrUpdate, useQualificationDelete, useQualificationExport, useQualificationIndex } from '@fl/api/anjutong/qualification-ticket'
import type { QualificationIndex } from '@fl/api/anjutong/model/qualification-ticket-model'
import { useDicts } from './hooks/use-dicts'
import dataScan from './components/data-scan.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'activity-manage-qualification-ticket',
})

const { dicts: { ActStatus } } = useDicts()

const { push } = useRouter()
const tableRef = ref()
const visible = ref<boolean>(false)
const scanId = ref<string>('')

// 搜索条件、分页参数
const initialState = {
    ticketName: '',
    projectName: '',
    isEnable: '',
}
const state = ref<QualificationIndex>(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

// 查询列表
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))
const { data, isLoading } = useQualificationIndex(params)
const records = ref<any>()

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records).reduce((pre, cur) => {
            cur.isEnable = cur.isEnable ? String(cur.isEnable) : '0'
            if (cur?.qualificationProjectRelevanceList?.length > 0) {
                const tempName = cur.qualificationProjectRelevanceList.reduce((pre2, cur2) => {
                    if (cur2.projectName) {
                        pre2 += `${cur2.projectName}、`
                    }
                    return pre2
                }, '')
                cur.projectName = tempName.slice(0, -1) // 去掉多余的、
            }

            // cur.formatNumberWithUnit()
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = data.value.total!
    }
})

// 删除
const { mutate: deleteMutate } = useQualificationDelete()
// 启用禁用
const { mutate: enableMutate } = useQualificationAddOrUpdate()

function switchStatus(row: any) {
    console.log('switchStatus', row.isEnable)
    const params = {
        ...row,
    }
    enableMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
        onError() {
            setTimeout(() => {
                row.isEnable = row.isEnable === 1 ? 0 : 1
            }, 500)
        },
    })
}

// 搜索
function submit(values: QualificationIndex) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = initialState
    tablePage.value = initialPage
}

// 新增
function goToAdd() {
    push({ name: 'qualification-ticket-add-or-edit' })
}

// 复制链接
function goToCopy(row: any) {
    push({ name: 'qualification-ticket-add-or-edit', query: { type: 'copy', id: row.id } })
}

// 列表：查看
function goToShow(row: any) {
    visible.value = true
    scanId.value = row.id || ''
}

// 列表：编辑
function goToEdit(row: any) {
    push({ name: 'qualification-ticket-add-or-edit', query: { type: 'edit', id: row.id } })
}

// 列表：删除
function deleteConfirm(row: any) {
    deleteMutate({ id: row.id }, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

// function formatNumberWithUnit(num) {
//     if (num >= 10000) {
//         return (num / 10000).toFixed(2) + ' 万';
//     }
//     return num;
// }

// 导出
const exportParams = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))
const { isPending, mutateAsync } = useQualificationExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        // const objectUrl = URL.createObjectURL(res)
        // location.href = objectUrl
        // URL.revokeObjectURL(objectUrl)
        const content = res
        const blob = new Blob([content])
        const d = new Date()
        const filename = `新房资格券_${d.getFullYear()}-${
            d.getMonth() + 1
        }-${d.getDate()}.xlsx`
        if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = filename
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        }
    }
}

const columns: PlusColumn[] = [
    {
        label: '资格券名称',
        prop: 'ticketName',
        valueType: 'copy',
    },
    {
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
    {
        label: '资格券状态',
        options: ActStatus,
        prop: 'isEnable',
        valueType: 'select',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'ticketName', title: '资格券名称' },
        { field: 'id', title: '资格券ID' },
        { field: 'projectName', title: '项目名称' },
        { field: 'startTime', title: '有效期开始时间' },
        { field: 'endTime', title: '有效期结束时间' },
        { field: 'grantQuantity', title: '每日发放数量' },
        { field: 'isEnable', slots: { default: 'isEnable' }, title: '资格券状态' },
        { field: 'qrCodeUrl', slots: { default: 'qrCodeUrl' }, title: '活动页小程序码' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 190 },
    ],
})
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />
    </ElCard>

    <div>
        <ElCard class="body"
                shadow="never"
        >
            <SearchTable ref="tableRef"
                         v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="records"
                         @page-change="handlePageChange"
            >
                <template #isEnable="{ row }">
                    <!-- {{ useDict('ActStatus', row.isEnable) }} -->
                    <el-switch v-model="row.isEnable"
                               active-value="1"
                               inactive-value="0"
                               inline-prompt
                               @change="switchStatus(row)"
                    />
                </template>

                <template #qrCodeUrl="{ row }">
                    <el-image v-if="row?.qrCodeUrl"
                              class="box"
                              :src="row.qrCodeUrl"
                              :preview-src-list="[row.qrCodeUrl]"
                              fit="contain"
                    />

                    <div v-else
                         class="box"
                    />
                </template>

                <template #toolbar_buttons>
                    <ElButton type="primary"
                              @click="goToAdd"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新增
                    </ElButton>

                    <ElButton type="primary"
                              plain
                              :loading="isPending"
                              @click="exportData"
                    >
                        <div class="i-iconamoon:upload size-16" />
                        导出
                    </ElButton>
                </template>

                <template #operate="{ row }">
                    <el-button class="small"
                               text
                               @click="goToCopy(row)"
                    >
                        复制
                    </el-button>

                    <el-button class="small"
                               text
                               @click="goToShow(row)"
                    >
                        数据
                    </el-button>

                    <el-button class="small"
                               type="primary"
                               text
                               @click="goToEdit(row)"
                    >
                        编辑
                    </el-button>

                    <el-popconfirm title="确认删除吗？"
                                   @confirm="deleteConfirm(row)"
                    >
                        <template #reference>
                            <el-button text
                                       type="warning"
                                       class="small"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </SearchTable>
        </ElCard>
    </div>

    <dataScan v-model:visible="visible"
              v-model:id="scanId"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
:deep(.el-tabs__nav-wrap::after) {
    display: none;
}
.box {
    width: 40px;
    height: 40px;
}
</style>
